<template>
  <Layout style="background:#fff;">
    <Form :model="formData" :label-width="100" :rules="rules" ref="refEdit">
      <!-- 运营账号 -->
      <div v-if="ROLE_OPERATION">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId" disabled>
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="用户名：" prop="username">
          <Input v-model.trim="formData.username" disabled />
        </FormItem>
        <FormItem label="姓名：" prop="name">
          <Input v-model.trim="formData.name" placeholder="请输入姓名..." clearable />
        </FormItem>
        <FormItem label="邮箱：" prop="email">
          <Input v-model.trim="formData.email" placeholder="请输入邮箱..." clearable />
        </FormItem>
        <FormItem label="电话：" prop="phone">
          <Input v-model.trim="formData.phone" placeholder="请输入电话..." clearable />
        </FormItem>
      </div>
      <!-- 省级账号 -->
      <div v-if="ROLE_PROVINCE">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId" disabled>
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="用户名：" prop="username">
          <Input v-model.trim="formData.username" disabled />
        </FormItem>
        <FormItem label="一级地域：" prop="areaId">
          <Select v-model="formData.areaId" placeholder="选择所属地域">
            <Option v-for="(item,index) in firstRegionList" :key="item.id" :label="item.name" :value="item.id" />
          </Select>
        </FormItem>
      </div>
      <!-- 市级账号 -->
      <div v-if="ROLE_CITY">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId">
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="用户名：" prop="username">
          <Input v-model.trim="formData.username" disabled />
        </FormItem>
        <FormItem label="二级地域：" prop="areaId">
          <Row>
            <Col span="11">
            <Select v-model="provinceId" placeholder="请选择一级地域" @on-change="getSecondRigion">
              <Option v-for="(item,index) in firstRegionList" :key="item.id" :label="item.name" :value="item.id" />
            </Select>
            </Col>
            <Col span="2" style="text-align:center;">
            -
            </Col>
            <Col span="11">
            <Select v-model="formData.areaId" placeholder="请选择二级地域">
              <Option v-for="(item,index) in secondAreaList" :key="item.id" :label="item.name" :value="item.id" />
            </Select>
            </Col>
          </Row>
        </FormItem>
      </div>
      <!-- 企业用户 -->
      <div v-if="ROLE_USER">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId" disabled>
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="用户名：" prop="username">
          <Input v-model.trim="formData.username" disabled />
        </FormItem>
        <FormItem label="所属企业：" prop="companyId">
          <Select v-model="formData.companyId" placeholder="选择所属企业" disabled>
            <Option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="姓名：" prop="name">
          <Input v-model.trim="formData.name" placeholder="请输入姓名..." clearable />
        </FormItem>
        <FormItem label="邮箱：" prop="email">
          <Input v-model.trim="formData.email" placeholder="请输入邮箱..." clearable />
        </FormItem>
        <FormItem label="电话：" prop="phone">
          <Input v-model.trim="formData.phone" placeholder="请输入电话..." clearable />
        </FormItem>
      </div>
      <!--  代理商 -->
      <div v-if="ROLE_PLATFORM">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId" disabled>
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
        <FormItem label="用户名：" prop="username">
          <Input v-model.trim="formData.username" disabled />
        </FormItem>
        <FormItem label="添加企业：" class="cover-ivu-form-item-lh" prop="companyIdList">
          <Treeselect v-model="formData.companyIdList" :options="treeData" :multiple="true" placeholder="选择代理企业" />
        </FormItem>
      </div>
    </Form>
    <Row style="text-align:right; border-top:1px solid #e8eaec;padding-top:15px;">
      <Button @click="onCancel">取消</Button>
      <Button @click="onSubmit" type="primary">提交</Button>
    </Row>
  </Layout>
</template>
<script>
import {
  getUserInformation,
  getUserGroupList,
  editUser,
  getRegionByParams,
  getRegionAll,
  getCompanyListOfNew,
  putUserAgent
} from "@/api";
import {
  validatePwd,
  validateAddress,
  validateEmail,
  validateTelephone
} from "@/utils/rules";
import { validateUserName } from "@/utils/validate";
import { buildTreeData } from "./utils";
export default {
  props: {
    userId: {
      type: String,
      default: ""
    }
  },
  mounted() {
    this.getRoleList();
    this.initData();
  },
  data() {
    const validatorCompanyIds = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("至少选择一个代理企业"));
      } else {
        callback();
      }
    };
    return {
      formData: {},
      roleList: [],
      firstRegionList: [],
      secondAreaList: [],
      companyList: [],
      provinceId: "",
      treeData: [],
      ROLE_CITY: false, // 市级账号
      ROLE_OPERATION: false, // 运营账号,
      ROLE_PROVINCE: false, // 省级账号
      ROLE_CITY: false, // 市级账号
      ROLE_USER: false, // 企业账号
      ROLE_PLATFORM: false, // 代理商账号
      rules: {
        roleId: [
          {
            required: true,
            message: "请选择用户组",
            trigger: "change"
          }
        ],
        username: [
          {
            required: "true",
            validator: validateUserName(
              "用户名",
              "用户名只能输入字母、数字、下划线、中划线并且不能小于4个字符"
            ),
            trigger: "blur"
          }
        ],
        companyIdList: [
          {
            required: true,
            validator: validatorCompanyIds,
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: validateAddress(
              "姓名",
              "姓名只能输入中文、字母、数字、下划线和中划线"
            )
          }
        ],
        email: [
          {
            required: true,
            validator: validateEmail("邮箱", "邮箱地址无效"),
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            validator: validateTelephone("电话", "手机号码格式不正确"),
            trigger: "blur"
          }
        ],
        areaId: [
          {
            required: true,
            message: "请选择所属地域",
            trigger: "change"
          }
        ],
        companyId: [
          {
            required: true,
            message: "请选择所属企业",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    // 获取用户组列表
    getRoleList() {
      getUserGroupList().then(res => {
        if (res.code === 200) {
          this.roleList = res.data;
        }
      });
    },

    // 获取一级地域列表
    getFirstRigion() {
      getRegionByParams({ type: 2 }).then(res => {
        if (res.code === 200) {
          this.firstRegionList = res.data;
        }
      });
    },

    // 获取二级地域
    getSecondRigion(provinceId) {
      const vm = this;
      vm.formData.areaId = "";
      const params = { provinceId };
      getRegionAll(params).then(res => {
        if (res.code === 200) {
          vm.secondAreaList = res.data.filter(t => t.belong !== "-");
        }
      });
    },

    // 获取企业列表
    getCompanyList() {
      getCompanyListOfNew({ size: 1000, page: 1 }).then(res => {
        if (res.code === 200) {
          this.companyList = res.data.list;
        }
      });
    },

    // 代理商获取企业列表
    getCompanyListForAgent() {
      return new Promise(resolve => {
        getCompanyListOfNew({ size: 1000, page: 1 }).then(res => {
          if (res.code === 200) {
            const list = res.data.list;
            this.treeData = buildTreeData(list);
            resolve();
          }
        });
      });
    },

    onSubmit() {
      const vm = this;
      vm.$refs.refEdit.validate(valid => {
        if (valid) {
          if (vm.ROLE_PLATFORM) {
            vm.saveAgent();
          } else {
            const params = JSON.parse(JSON.stringify(vm.formData));
            params.id = vm.userId;
            editUser(params).then(res => {
              if (res.code === 200) {
                vm.$Message.success("操作成功");
                vm.$emit("save");
              } else {
                vm.$Message.error(res.message);
              }
            });
          }
        }
      });
    },

    // 保存代理商
    saveAgent() {
      const vm = this;
      const params = JSON.parse(JSON.stringify(vm.formData));
      params.id = vm.userId;
      params.companyIds = vm.formData.companyIdList.join(",");
      delete params.companyIdList;
      putUserAgent(params).then(res => {
        if (res.code === 200) {
          vm.$Message.success("操作成功");
          vm.$emit("save");
        } else {
          vm.$Message.error(res.message);
        }
      });
    },

    onCancel() {
      this.$emit("off");
    },

    initData() {
      const vm = this;
      const { userId } = vm;
      if (vm.ROLE_OPERATION) vm.ROLE_OPERATION = false;

      if (vm.ROLE_PLATFORM) vm.ROLE_PLATFORM = false;

      if (vm.ROLE_PROVINCE) vm.ROLE_PROVINCE = false;

      if (vm.ROLE_CITY) vm.ROLE_CITY = false;

      if (vm.ROLE_USER) vm.ROLE_USER = true;

      getUserInformation({ userId }).then(res => {
        if (res.code === 200) {
          const { groupName } = res.data;
          switch (groupName) {
            case "ROLE_OPERATION":
              vm.INIT_ROLE_OPERATION(res.data);
              break;
            case "ROLE_PLATFORM":
              vm.INIT_ROLE_PLATFORM(res.data);
              break;
            case "ROLE_PROVINCE":
              vm.INIT_ROLE_PROVINCE(res.data);
              break;
            case "ROLE_CITY":
              vm.INIT_ROLE_CITY(res.data);
              break;
            case "ROLE_USER":
              vm.INIT_ROLE_USER(res.data);
              break;
          }
        }
      });
    },

    // 初始化运营账号
    INIT_ROLE_OPERATION(data) {
      const vm = this;
      const { userGroup, username, name, email, phone } = data;
      vm.formData = {
        roleId: userGroup,
        username,
        name,
        email,
        phone,
        areaId: "",
        companyId: ""
      };
      vm.ROLE_OPERATION = true;
    },

    // 初始化省级账号
    INIT_ROLE_PROVINCE(data) {
      const vm = this;
      const { areaId, username, userGroup } = data;
      vm.getFirstRigion();
      vm.formData = {
        roleId: userGroup,
        username,
        areaId,
        name: "",
        email: "",
        phone: "",
        companyId: ""
      };
      vm.ROLE_PROVINCE = true;
    },

    // 初始化市级账号
    INIT_ROLE_CITY(data) {
      const vm = this;
      vm.getFirstRigion();
      const { parentAreaId, areaId, userGroup, username } = data;
      vm.provinceId = parentAreaId;
      vm.formData = {
        areaId,
        roleId: userGroup,
        username,
        name: "",
        email: "",
        phone: "",
        companyId: ""
      };
      getRegionAll({ provinceId: parentAreaId }).then(res => {
        if (res.code === 200) {
          vm.secondAreaList = res.data.filter(t => t.belong !== "-");
        }
      });
      vm.ROLE_CITY = true;
    },

    // 初始化企业账号
    INIT_ROLE_USER(data) {
      const vm = this;
      var companyId = null;
      vm.getCompanyList();
      const { companyIds, userGroup, username, name, email, phone } = data;
      companyId = companyIds;
      vm.formData = {
        roleId: userGroup,
        username,
        name,
        email,
        phone,
        companyId,
        areaId: ""
      };
      vm.ROLE_USER = true;
    },

    // 初始化代理商
    INIT_ROLE_PLATFORM(data) {
      const vm = this;
      const { userGroup, username, name, email, phone, companyIds } = data;
      vm.getCompanyListForAgent().then(() => {
        const companyIdList = companyIds.split(",");
        vm.formData = {
          roleId: userGroup,
          username,
          name,
          email,
          phone,
          areaId: "",
          companyId: "",
          companyIdList
        };
        vm.ROLE_PLATFORM = true;
      });
    }
  }
};
</script>
